﻿using Microsoft.Extensions.DependencyInjection;
using SqlSugar;

namespace DAL
{
    public static class DB
    {
        public static ISqlSugarClient SqlSugarClient { get; set; }

        public static void AddSqlSugarSetup(this IServiceCollection services, SqlSugar.DbType dbtype, string connectStr)
        {
            //数据库初始化
            services.AddSingleton<ISqlSugarClient>(s =>
            {
                SqlSugarClient = new SqlSugarScope(new ConnectionConfig()
                {
                    DbType = dbtype,
                    ConnectionString = connectStr,
                    IsAutoCloseConnection = true,
                },
               db =>
               {
                   //每次上下文都会执行

                   //获取IOC对象不要求在一个上下文
                   //var log=s.GetService<Log>()

                   //获取IOC对象要求在一个上下文
                   //var appServive = s.GetService<IHttpContextAccessor>();
                   //var log= appServive?.HttpContext?.RequestServices.GetService<Log>();
#if DEBUG
                   db.Aop.OnLogExecuting = (sql, pars) =>
                   {
                       //Console.WriteLine(sql);
                   };
#endif
               });
                return SqlSugarClient;
            });
        }
    }
}
